<template>
  <div>

    <v-form v-model="valid" ref="heima60">
      <v-text-field label="请输入品牌名称" v-model="brand.name" required :rules="nameRules"></v-text-field>
      <v-text-field label="请输入品牌首字母" v-model="brand.letter" required :rules="letterRules"></v-text-field>
      <v-cascader
        url="/item/category/list"
        multiple
        required
        v-model="brand.categories"
        label="请选择商品分类"/>
      <v-layout row>
        <v-flex xs3>
          <span style="font-size: 16px; color: #444">品牌LOGO：</span>
        </v-flex>
        <v-flex>
          <v-upload
            v-model="brand.image"
            url="/upload/image"
            :multiple="false"
            :pic-width="250"
            :pic-height="90"
          />
        </v-flex>
      </v-layout>
      <v-spacer/>
      <v-btn @click="clear" class="warning">重置</v-btn>
      <v-btn @click="submit" class="info">提交</v-btn>
    </v-form>

  </div>
</template>

<script>
  export default {
    name: "MyBrandForm",
    props:{
      oldBrand:{
        type:Object,
        default:{}
      },
      edit:{
        type:Boolean,
        default: false
      }
    },
    data() {
      return {
        valid:false,
        nameRules:[
          v => !!v || "品牌名称不能为空",
          v => v.length > 1 || "品牌名称至少2位"
        ],
        letterRules:[
          v => !!v || "首字母不能为空",
          v => /^[A-Z]{1}$/.test(v) || "品牌字母只能是A~Z的大写字母"
        ],
        brand:{
          name:"",
          letter:"",
          image:"",
          categories:[]
        }
      }
    },
    methods:{
      submit(){
        // 提交表单

        if (this.$refs.heima60.validate()) {

          //解构brand对象，取出分类数组
          let {categories,...others} = this.brand;

          //从分类数组中把分类id取出
          let result = categories.map(ele=>ele.id);

          //把分类id数组转为分类id的字符串，并且把cids封装给others数据对象
          others.cids = result.join();//把数组变成字符串


          // 将数据提交到后台
          // this.$http.post('/item/brand', this.$qs.stringify(params))
          this.$http({
            method: this.edit ? 'put' : 'post', // 动态判断是POST还是PUT
            url: '/item/brand',
            data: this.$qs.stringify(others)
          }).then(() => {
            // 关闭窗口
            this.$emit("close");
            this.$message.success("保存成功！");
          })
            .catch(() => {
              this.$message.error("保存失败！");
            });
        }else{
          alert("表单数据有误");
        }
      },
      clear(){
        // 重置表单
        //如何找到表单呢？？？？
        this.$refs.heima60.reset();

        //reset方法可以清掉原生组件的所有信息，但是只会清除自定义组件的表面信息，
        this.brand.categories=[];
      }
    },
    watch:{
      oldBrand:{
        deep:true,
        handler(){
          this.brand = this.oldBrand;
        }
      }
    }
  }
</script>

<style scoped>

</style>
